package cn.kgc.vue.controller;

import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Permission;
import cn.kgc.vue.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/7/5
 * @description
 */
@RestController
@RequestMapping("permission")
@Api(tags = "权限模块")
public class PermissionController {


    @Resource
    private PermissionService permissionService;

    @GetMapping("tree")
    @ApiOperation("权限树形列表")
    public ResponseResult treeList() {

        LambdaQueryWrapper<Permission> lambda = new QueryWrapper<Permission>().lambda();
        lambda.select(Permission::getId,Permission::getPid,Permission::getTitle,Permission::getIsMenu);
        List<Permission> list = permissionService.list(lambda);
        return  ResponseResult.success().data("treeList",list);
    }

    @GetMapping("list")
    @ApiOperation("权限列表")
    public ResponseResult permissionList() {
        List<Permission> list = permissionService.list();
        return  ResponseResult.success().data("permissionList",list);
    }


    @PostMapping("addOrUpdate")
    @ApiOperation("新增/编辑权限")
    public ResponseResult addPermission(@RequestBody Permission permission) {

        //  调用修改和添加的方法    包含id  update   否则  insert
        permissionService.saveOrUpdate(permission);
        return  ResponseResult.success().message("操作成功");
    }


    @DeleteMapping ("delete/{id}")
    @ApiOperation("删除权限")
    public ResponseResult deletePermission(@PathVariable("id")Integer id) {

        return  permissionService.deletePermission(id);
    }

    @GetMapping("getOne/{id}")
    @ApiOperation("获取一个权限信息")
    public ResponseResult getOnePermission(@PathVariable("id") Integer id) {
        Permission permission = permissionService.getById(id);
        Integer pid = permission.getPid();
        // 获取父菜单的title
        String title = "";
        Permission permission2 = permissionService.getById(pid);
        if (ObjectUtils.isNotNull(permission2)){
            title= permission2.getTitle();
        }

        return  ResponseResult.success().data("permission",permission).data("parentTitle",title);
    }
}
